package tcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;
    private int port;
    public TcpEchoServer(int port) throws IOException {
        this.port = port;
        serverSocket = new ServerSocket(port);
    }

    public void processConnect(Socket clientSocket){
            try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()))) {

                while (true) { // 当链接断开的时候 就会触发异常 结束 循环
                    String request = bufferedReader.readLine();
                    String response = process(request);
                    bufferedWriter.write(response +"\n");
                    bufferedWriter.flush();
                    System.out.printf("[%s:%d] req: %s ,resp: %s\n",clientSocket.getInetAddress().toString(),clientSocket.getPort(),
                                                request,response);
                }

            } catch (IOException e) {
                System.out.printf("[%s:%d] 断开连接\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
            }
    }

    private String process(String request) {
        return request;
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            Socket clientSocket = serverSocket.accept();
            processConnect(clientSocket);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9191);
        tcpEchoServer.start();
    }
}
